package com.pai4j.common.config.annotation;


import com.pai4j.common.constants.WebConstant;
import com.pai4j.common.exception.AuthException;
import com.pai4j.common.exception.SafeEventException;
import com.pai4j.common.helper.SessionHelper;
import com.pai4j.common.util.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/***
 * 异常点击事件拦截
 */
@Slf4j
public class SafeClickInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    /***
     * 在调用方法之前执行拦截
     */
   
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        SafeClick safeClick = method.getAnnotation(SafeClick.class);

        if (safeClick == null) {
            return true;
        }
        // 操作人
        String userId = SessionHelper.getCurrentUserId();
        if (StringUtils.isBlank(userId)) {
            throw new AuthException("未登录！");
        }
        // 事件
        String action = safeClick.event().name();
        // 允许多长时间操作一次
        long liveTime = safeClick.time();
        String key = action.concat("-").concat(userId);
        boolean installLockResult = redisUtil.installLockForMS(key, WebConstant.CACHE_NONE, liveTime);
        if (installLockResult) {
            return true;
        }
        log.error("<<<< {} >>>>, Trace-Id: {}, userId: {}, action: {}",
                SessionHelper.getTraceId(), safeClick.message(), userId, action);
        throw new SafeEventException(safeClick.message());
    }

}